package com.school.base.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;

import com.school.base.dao.IClassDao;
import com.school.base.model.Class;
import com.school.common.base.BaseDao;
import com.school.common.util.MapUtils;

public class ClassDao extends BaseDao implements IClassDao {

	@Override
	public Class getClassById(int id) {
		return (Class) this.getObjectById(Class.class, id);
	}

	private String getExpressSql(Class cls, List express) {
		String sql = "";
		if (cls != null) {
			if (cls.getName() != null && !cls.getName().isEmpty()) {
				sql += " and c.name like ?";
				express.add("%" + cls.getName() + "%");
			}
			if (cls.getGrade() != null && !cls.getGrade().isEmpty()) {
				sql += " and c.grade=?";
				express.add(cls.getGrade());
			}
		}
		return sql;
	}

	@Override
	public List<Class> getClassList(Class cls, int offset, int pageSize) {
		String sql = "select *,t.real_name headerName from b_class c left join b_teacher t on t.id=c.header_id where 1=1";
		List express = new ArrayList();
		sql += this.getExpressSql(cls, express);
		SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		if (express != null) {
			for (int i = 0; i < express.size(); i++) {
				query.setParameter(i, express.get(i));
			}
		}
		query.setMaxResults(pageSize);
		query.setFirstResult(offset);
		List list = query.list();
		List<Class> classList = new ArrayList<Class>();
		for (Object obj : list) {
			Class c = (Class) MapUtils.mapToBean((HashMap<String, Object>) obj, Class.class);
			classList.add(c);
		}
		return classList;
	}

	@Override
	public int getTotalCount(Class cls) {
		String sql = "select count(*) from b_class c left join b_teacher t on t.id=c.header_id where 1=1";
		List express = new ArrayList();
		sql += this.getExpressSql(cls, express);
		return this.getRecordCountBySql(sql, express);
	}

	@Override
	public void updateClass(Class cls) {
		this.update(cls);
	}

	@Override
	public void deleteClass(int id) {
		Class cls = new Class();
		cls.setId(id);
		this.delete(cls);
	}

	@Override
	public void insertClass(Class cls) {
		cls.setCreateTime(new Date());
		this.insert(cls);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.school.base.dao.IClassDao#getAllUnexpiredByGrade(java.lang.String)
	 */
	@Override
	public List<Class> getAllUnexpiredByGrade(String grade) {
		List<Criterion> express = new ArrayList<Criterion>();
		express.add(Restrictions.eq("grade", grade));
		express.add(Restrictions.le("endDate",new Date()));
		return this.getList(Class.class, express, null);
	}
}
